package cn.yuanqiao.archive.supervision.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.yuanqiao.archive.appManager.domain.TenantRyMjDzb;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.supervision.domain.*;
import cn.yuanqiao.archive.supervision.mapper.AddAnnualInspectionMaterialsMapper;
import cn.yuanqiao.archive.supervision.mapper.AnnualInspectionNoticeMapper;
import cn.yuanqiao.archive.supervision.service.AnnualInspectionNoticeService;
import cn.yuanqiao.archive.utils.BeanHelper;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.*;
import cn.yuanqiao.manage.domain.ManageTenant;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : 庸人一个
 * @create : 2024/3/13 15:28
 */
@Slf4j
@Service
public class AnnualInspectionNoticeServiceImpl implements AnnualInspectionNoticeService {

    @Autowired
    @Lazy
    private AnnualInspectionNoticeService service;

    @Autowired
    private AnnualInspectionNoticeMapper annualInspectionNoticeMapper;

    @Autowired
    private AddAnnualInspectionMaterialsMapper addAnnualInspectionMaterialsMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private TenantMijiComparisonTableServiceImpl mijiComparisonTableService;

    @Override
    @Transactional
    public int save(AnnualVo vo) {
        YqAnnualCheckNotices annualCheckNotices = BeanHelper.copyProperties(vo, YqAnnualCheckNotices.class);
        annualCheckNotices.setCreateTime(DateUtils.getNowDate());
        annualCheckNotices.setCreateUser(SecurityUtils.getUsername());
        annualCheckNotices.setTenantcode(SecurityUtils.getTenantCode());
        int save = annualInspectionNoticeMapper.save(annualCheckNotices);
        log.info("保存年检通知单信息，结果：{}", save > 0 ? "成功" : "失败");
        if (save <= 0) {
            throw new RuntimeException("保存年检通知单信息失败");
        }
        Long id = annualCheckNotices.getId();
        if (CollectionUtils.isNotEmpty(vo.getAttachmentsList())) {
            List<YqAttachmentsNotices> attachmentsNoticesList = new ArrayList<>();
            vo.getAttachmentsList().forEach(item -> {
                attachmentsNoticesList.add(
                        YqAttachmentsNotices.builder()
                                .noticesId(id)
                                .attachmentsId(item.getId())
                                .attachmentsType(item.getFileType())
                                .build()
                );

            });
            int r = annualInspectionNoticeMapper.saveAnnuAndFileBatch(attachmentsNoticesList);
            log.info("保存年检通知单附件信息，结果：{}", r > 0 ? "成功" : "失败");
            if (r <= 0) {
                throw new RuntimeException("保存年检通知单附件信息失败");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public AjaxResult uploadFile(MultipartFile file, String type, Long id, String mj) {
        //判断文件是否可用
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置文件存储路径
//        String filePath = "D:\\upload\\";
        String filePath = sysConfigService.selectConfigByKey("YQ_MNT");
        if(StringUtils.isEmpty(filePath)){
            throw new ServiceException("系统参数错误YQ_MNT未找到配置！");
        }
        filePath = filePath + "/zhidao/"+DateUtil.format(new Date(), "yyyyMMdd") + "/";;
        //按照当前日期创建层级目录
        //文件名重新命名
        String fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        long fileId = SnowflakeIdGenerator.generateId();
        try {
            //保存文件
            file.transferTo(dest);
            YqAttachments build = YqAttachments.builder()
                    .id(fileId)
                    .fileName(fileName)
                    .fileType(type)
                    .filePath(dest.getPath())
                    .originalFile(originalFilename)
                    .mj(mj)
                    .build();
            int r = annualInspectionNoticeMapper.saveFile(build);
            //添加中间表
            if (id != null) {
                List<YqAttachmentsNotices> buildList = new ArrayList<>();
                buildList.add( YqAttachmentsNotices.builder()
                        .noticesId(id)
                        .attachmentsId(fileId)
                        .attachmentsType(type)
                        .build());
                annualInspectionNoticeMapper.saveAnnuAndFileBatch(buildList);
            }
            return AjaxResult.success(build);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("上传失败");
    }

    @Override
    public YqAttachments findByFileId(Long id) {
        return annualInspectionNoticeMapper.findByFileId(id);
    }

    @Override
    @Transactional
    public int deleteFile(YqAttachmentsNotices attachmentsNotices) {
        try {
            YqAttachments yqAttachments = annualInspectionNoticeMapper.findByFileId(attachmentsNotices.getAttachmentsId());
            if (yqAttachments == null) {
                return -1;
            }
            // 删除附件表
            int r = annualInspectionNoticeMapper.deleteFile(attachmentsNotices.getAttachmentsId());
            if (attachmentsNotices.getAttachmentsId() != null &&
                    attachmentsNotices.getNoticesId() != null &&
                    attachmentsNotices.getAttachmentsType() != null) {
                int count = annualInspectionNoticeMapper.findFileCount(attachmentsNotices);
                if (count > 0) {
                    //删除中间表
                    int zr = annualInspectionNoticeMapper.deleteYqAttachmentsNotices(attachmentsNotices);
                }
            }
            File file = new File(yqAttachments.getFilePath());
            if (file.exists()) {
                file.delete();
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除文件失败");
        }
    }

    @Override
    @Transactional
    public int deleteById(Long id) {
        try {
            //1.根据id查询中间表
            YqAttachmentsNotices build = YqAttachmentsNotices.builder()
                    .noticesId(id)
                    .build();
            List<YqAttachmentsNotices> list = annualInspectionNoticeMapper.findByAnnualInspectionNoticeId(build);
            //2.根据文件id删除文件
            if (CollectionUtils.isNotEmpty(list)) {
                //3.删除中间表与附件表
                list.forEach(service::deleteFile);
            }
            //4.逻辑删除通知表
            int ar = annualInspectionNoticeMapper.updateById(id);
            return ar;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    @Transactional
    public int update(AnnualVo vo) {
        try {
            vo.setUpdateUser(SecurityUtils.getUsername());
            vo.setUpdateTime(DateUtils.getNowDate());
            vo.setTenantCode(SecurityUtils.getTenantCode());
            //1.按照id修改年检通知表
            int ar = annualInspectionNoticeMapper.update(vo);
            //2.判断附件是否存在，如果不存在，添加附件
            if (CollectionUtils.isNotEmpty(vo.getAttachmentsList())) {
                List<YqAttachmentsNotices> list = new ArrayList<>();
                vo.getAttachmentsList().forEach(item -> {
                    YqAttachmentsNotices build = YqAttachmentsNotices.builder()
                            .noticesId(vo.getId())
                            .attachmentsId(item.getId())
                            .attachmentsType(item.getFileType())
                            .build();
                    List<YqAttachmentsNotices> yqAttachmentsNotices = annualInspectionNoticeMapper.findByAnnualInspectionNoticeId(build);
                    if (CollectionUtils.isEmpty(yqAttachmentsNotices)) {
                        list.add(YqAttachmentsNotices.builder()
                                .attachmentsId(item.getId())
                                .attachmentsType(item.getFileType())
                                .noticesId(vo.getId())
                                .build());
                    }
                });
                if (CollectionUtils.isNotEmpty(list)) {
                    int r = annualInspectionNoticeMapper.saveAnnuAndFileBatch(list);
                }
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("修改年检通知表失败");
        }

    }

    @Override
    public List<AnnualVo> findPage(AnnualVo vo) {
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        vo.setTenantCode(SecurityUtils.getTenantCode());
        return annualInspectionNoticeMapper.findByPage(vo);
    }

    @Override
    public AnnualVo findById(Long id) {
        AnnualVo vo = annualInspectionNoticeMapper.findById(id);
        if (vo != null) {
            String mjWhere = "";
            if(FBswitch){
                List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
                mjWhere=(" and a.MJ in ('" + getdamjbyrymj.stream().map(m->m.getDaMj()).collect(Collectors.joining("','")) +"') ");
            }
            List<YqAttachments> attachmentsList = annualInspectionNoticeMapper.findFile(id,mjWhere);
            vo.setAttachmentsList(attachmentsList);
            return vo;
        }
        return null;
    }

    @Override
    @Transactional
    public void send(JSONObject object) {
        String id = object.get("id").toString();
        List manageTenants = (List) object.get("manageTenant");
        String date = object.get("deadLine").toString();
        if (id == null) {
            throw new RuntimeException("参数错误");
        }
        if(CollectionUtils.isEmpty(manageTenants)){
            throw new RuntimeException("单位不能为空");
        }
        AnnualVo vo = annualInspectionNoticeMapper.findById(Long.parseLong(id));
        if (vo == null) {
            throw new RuntimeException("数据不存在");
        }
        String mjWhere = "";
        if(FBswitch){
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            mjWhere=(" and a.MJ in ('" + getdamjbyrymj.stream().map(m->m.getDaMj()).collect(Collectors.joining("','")) +"') ");
        }
        List<YqAttachments> file = annualInspectionNoticeMapper.findFile(vo.getId(),mjWhere);
        for (Object o : manageTenants) {
            ManageTenant manageTenant =JSONObject
                    .parseObject(JSONObject.toJSONString(o), ManageTenant.class);
           // 初始化一个YqIssuedNotice对象，传入参数vo，manageTenant，date
            YqIssuedNotice issuedNotice = YqIssuedNotice.init(vo, manageTenant, date);
            addAnnualInspectionMaterialsMapper.save(issuedNotice);
            //添加附件中间表
            List<YqAttachmentsNotices> list = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(file)) {
                file.forEach(item -> {
                    list.add(YqAttachmentsNotices.builder()
                            .attachmentsId(item.getId())
                            .attachmentsType(item.getFileType())
                            .noticesId(issuedNotice.getId())
                            .build());
                });
            }
            if (CollectionUtils.isNotEmpty(list)) {
                int r = annualInspectionNoticeMapper.saveAnnuAndFileBatch(list);
            }
        }
        service.update(AnnualVo.builder()
                .id(vo.getId())
                .isIssueNotice("1")
                .build());
    }

    @Override
    public List<ManageTenant> findUnit(Map<String, Object> map) {
        String tenantCode = SecurityUtils.getTenantCode();
        List<ManageTenant> list = annualInspectionNoticeMapper.findUnit(tenantCode);
        String type = map.get("type").toString();
        switch (type) {
            case "1":
                return list;
            case "2":
                Integer number = (Integer) map.get("number");
                if (number == null) {
                    throw new RuntimeException("随机单位数量不能为空");
                }
                //根据number的数量，随机收取list
                if (number > list.size()) {
                    throw new RuntimeException("随机单位数量，超出总单位数量，总单位数量为：" + list.size());
                }
                Collections.shuffle(list);
                return list.subList(0, number);
            default:
                return null;
        }
    }
}
